<template>
  <div class="quality-analysis-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>质量分析</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleExport">导出报告</el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="统计周期">
          <el-select v-model="queryForm.period" @change="handlePeriodChange">
            <el-option label="本月" value="month" />
            <el-option label="本季度" value="quarter" />
            <el-option label="本年" value="year" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="queryForm.period === 'custom'">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="产品类型">
          <el-select v-model="queryForm.productType" clearable>
            <el-option
              v-for="item in productTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 质量概览卡片 -->
      <el-row :gutter="20" class="dashboard-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>合格率</span>
                <el-tag
                  :type="getQualifiedRateTag(qualityOverview.qualifiedRate)"
                >
                  {{ qualityOverview.qualifiedRate }}%
                </el-tag>
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ qualityOverview.qualifiedRate }}%</div>
              <div
                class="trend"
                :class="qualityOverview.qualifiedRateTrend > 0 ? 'up' : 'down'"
              >
                较上期{{ Math.abs(qualityOverview.qualifiedRateTrend) }}%
                <i
                  :class="
                    qualityOverview.qualifiedRateTrend > 0
                      ? 'el-icon-top'
                      : 'el-icon-bottom'
                  "
                />
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>不合格品数</span>
                <el-tag type="danger"
                  >{{ qualityOverview.defectCount }}件</el-tag
                >
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ qualityOverview.defectCount }}</div>
              <div
                class="trend"
                :class="qualityOverview.defectCountTrend < 0 ? 'up' : 'down'"
              >
                较上期{{ Math.abs(qualityOverview.defectCountTrend) }}%
                <i
                  :class="
                    qualityOverview.defectCountTrend < 0
                      ? 'el-icon-top'
                      : 'el-icon-bottom'
                  "
                />
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>客户投诉</span>
                <el-tag type="warning"
                  >{{ qualityOverview.complaintCount }}起</el-tag
                >
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ qualityOverview.complaintCount }}</div>
              <div
                class="trend"
                :class="qualityOverview.complaintCountTrend < 0 ? 'up' : 'down'"
              >
                较上期{{ Math.abs(qualityOverview.complaintCountTrend) }}%
                <i
                  :class="
                    qualityOverview.complaintCountTrend < 0
                      ? 'el-icon-top'
                      : 'el-icon-bottom'
                  "
                />
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>质量成本</span>
                <el-tag type="info">{{ qualityOverview.qualityCost }}万</el-tag>
              </div>
            </template>
            <div class="card-content">
              <div class="number">{{ qualityOverview.qualityCost }}万</div>
              <div
                class="trend"
                :class="qualityOverview.qualityCostTrend < 0 ? 'up' : 'down'"
              >
                较上期{{ Math.abs(qualityOverview.qualityCostTrend) }}%
                <i
                  :class="
                    qualityOverview.qualityCostTrend < 0
                      ? 'el-icon-top'
                      : 'el-icon-bottom'
                  "
                />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <div class="charts-container">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>合格率趋势</span>
              <el-radio-group v-model="qualifiedRateChartType" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="quarter">季</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="qualifiedRateChart" class="chart"></div>
        </el-card>

        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>不合格原因分布</span>
              <el-radio-group v-model="defectChartType" size="small">
                <el-radio-button label="count">数量</el-radio-button>
                <el-radio-button label="cost">成本</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="defectReasonChart" class="chart"></div>
        </el-card>
      </div>

      <!-- 质量问题TOP10 -->
      <el-card class="mt-20">
        <template #header>
          <div class="card-header">
            <span>质量问题TOP10</span>
          </div>
        </template>
        <el-table :data="qualityIssueTop10" border style="width: 100%">
          <el-table-column prop="rank" label="排名" width="80" align="center" />
          <el-table-column prop="issue" label="问题描述" min-width="200" />
          <el-table-column
            prop="count"
            label="发生次数"
            width="100"
            align="center"
          />
          <el-table-column
            prop="percentage"
            label="占比"
            width="100"
            align="center"
          >
            <template #default="scope"> {{ scope.row.percentage }}% </template>
          </el-table-column>
          <el-table-column prop="trend" label="趋势" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.trend === 'up' ? 'danger' : 'success'">
                {{ scope.row.trend === "up" ? "上升" : "下降" }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";

// 查询表单
const queryForm = reactive({
  period: "month",
  dateRange: [],
  productType: "",
});

// 产品类型选项
const productTypeOptions = [
  { label: "机械零件", value: "mechanical" },
  { label: "电子元件", value: "electronic" },
  { label: "液压件", value: "hydraulic" },
  { label: "标准件", value: "standard" },
];

// 质量概览数据
const qualityOverview = reactive({
  qualifiedRate: 98.5,
  qualifiedRateTrend: 0.5,
  defectCount: 156,
  defectCountTrend: -3.2,
  complaintCount: 12,
  complaintCountTrend: -5.0,
  qualityCost: 23.5,
  qualityCostTrend: -2.8,
});

// 图表类型
const qualifiedRateChartType = ref("month");
const defectChartType = ref("count");

// 图表引用
const qualifiedRateChart = ref(null);
const defectReasonChart = ref(null);
let charts = [];

// 质量问题TOP10数据
const qualityIssueTop10 = ref([
  { rank: 1, issue: "表面划痕", count: 45, percentage: 15.8, trend: "down" },
  { rank: 2, issue: "尺寸超差", count: 38, percentage: 13.3, trend: "up" },
  { rank: 3, issue: "装配间隙", count: 32, percentage: 11.2, trend: "down" },
  { rank: 4, issue: "焊接缺陷", count: 28, percentage: 9.8, trend: "up" },
  { rank: 5, issue: "材料缺陷", count: 25, percentage: 8.7, trend: "down" },
  { rank: 6, issue: "外观不良", count: 22, percentage: 7.7, trend: "down" },
  { rank: 7, issue: "性能不达标", count: 18, percentage: 6.3, trend: "up" },
  { rank: 8, issue: "零件缺失", count: 15, percentage: 5.2, trend: "down" },
  { rank: 9, issue: "标识错误", count: 12, percentage: 4.2, trend: "down" },
  { rank: 10, issue: "包装破损", count: 10, percentage: 3.5, trend: "up" },
]);

// 合格率标签颜色
const getQualifiedRateTag = (rate) => {
  if (rate >= 98) return "success";
  if (rate >= 95) return "warning";
  return "danger";
};

// 初始化图表
onMounted(() => {
  initQualifiedRateChart();
  initDefectReasonChart();
  window.addEventListener("resize", handleResize);
});

// 销毁图表
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  charts.forEach((chart) => chart.dispose());
});

// 窗口大小改变时重绘图表
const handleResize = () => {
  charts.forEach((chart) => chart.resize());
};

// 初始化合格率趋势图
const initQualifiedRateChart = () => {
  const chart = echarts.init(qualifiedRateChart.value);
  charts.push(chart);

  const option = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["合格率", "目标值"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["1月", "2月", "3月", "4月", "5月", "6月"],
    },
    yAxis: {
      type: "value",
      min: 90,
      max: 100,
      axisLabel: {
        formatter: "{value}%",
      },
    },
    series: [
      {
        name: "合格率",
        type: "line",
        data: [98.5, 98.2, 98.8, 97.9, 98.6, 99.0],
        smooth: true,
        markLine: {
          data: [
            {
              name: "目标线",
              yAxis: 98,
            },
          ],
        },
      },
    ],
  };

  chart.setOption(option);
};

// 初始化不合格原因分布图
const initDefectReasonChart = () => {
  const chart = echarts.init(defectReasonChart.value);
  charts.push(chart);

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
    },
    series: [
      {
        type: "pie",
        radius: ["50%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "16",
            fontWeight: "bold",
          },
        },
        data: [
          { value: 45, name: "表面缺陷" },
          { value: 38, name: "尺寸问题" },
          { value: 32, name: "装配问题" },
          { value: 28, name: "焊接缺陷" },
          { value: 25, name: "材料问题" },
        ],
      },
    ],
  };

  chart.setOption(option);
};

// 处理函数
const handlePeriodChange = () => {
  if (queryForm.period !== "custom") {
    queryForm.dateRange = [];
  }
};

const handleSearch = () => {
  ElMessage.success("数据已更新");
};

const handleReset = () => {
  queryForm.period = "month";
  queryForm.dateRange = [];
  queryForm.productType = "";
};

const handleExport = () => {
  ElMessage.success("报告导出成功");
};
</script>

<style scoped>
.quality-analysis-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.dashboard-cards {
  margin-bottom: 20px;
}

.card-header-small {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.card-content {
  text-align: center;
}

.number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin: 10px 0;
}

.trend {
  font-size: 12px;
  color: #909399;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 350px;
}

.mt-20 {
  margin-top: 20px;
}
</style>
